﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace MvcToolbox
{
    public class FeatureToggle
    {
        public static bool IsActive(string key)
        {
            FeatureToggleSection config = (FeatureToggleSection)System.Configuration.ConfigurationManager.GetSection("FeatureToggle");
            for (int i = 0; i < config.Features.Count; i++)
            {
                FeatureElement elt = config.Features[i];
                if (elt.Name == key)
                {
                    return ComputeIsActive(elt);
                }
            }
            return false;
        }

        private static bool ComputeIsActive(FeatureElement elt)
        {
            if (elt.IsActive.HasValue && elt.IsActive.Value && elt.ActivateAfterDate.IsNullOrEmpty() && elt.DesactivateAfterDate.IsNullOrEmpty())
            {
                return elt.IsActive.Value;
            }
            else if (elt.IsActive.Value && !elt.DesactivateAfterDate.IsNullOrEmpty())
            {
                DateTime dt = DateTime.Parse(elt.DesactivateAfterDate);
                return (DateTime.Now >= dt) ? false : true;
            }
            else if (!elt.IsActive.Value && !elt.ActivateAfterDate.IsNullOrEmpty())
            {
                DateTime dt = DateTime.Parse(elt.ActivateAfterDate);
                return (DateTime.Now >= dt) ? true : false;
            }
            else if (!elt.ActivateAfterDate.IsNullOrEmpty() && !elt.DesactivateAfterDate.IsNullOrEmpty())
            {
                DateTime dtActivate = DateTime.Parse(elt.ActivateAfterDate);
                DateTime dtDesactivate = DateTime.Parse(elt.DesactivateAfterDate);
                if (dtActivate < dtDesactivate)
                {
                    if (DateTime.Now >= dtActivate && DateTime.Now <= dtDesactivate)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    if (DateTime.Now >= dtDesactivate && DateTime.Now <= dtActivate)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
            }

            
            return false;
        }

    }
}
